package cn.sunzq.springdata.elasticsearch.demo.utils;

import cn.sunzq.springdata.elasticsearch.demo.base.BaseService;
import lombok.SneakyThrows;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

/**
 * @创建人 孙中泉
 * @创建时间 2021/7/21
 * @描述
 */
@Component
public class EsRestHighLevelClientUtil extends BaseService {

    @SneakyThrows
    public boolean indexExists(String indexName)  {
        return  restHighLevelClient.indices().exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);
    }

    @SneakyThrows
    public boolean createIndexWithJsonString(String indexName, String mappingSource) {
        if(!this.indexExists(indexName)){
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            createIndexRequest.settings(Settings.builder()
                    .put("index.number_of_shards", 1)
                    .put("index.number_of_replicas", 0)
            );
            createIndexRequest.mapping(mappingSource, XContentType.JSON);
            restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        }
        return true;
    }
}
